package com.sgb.kjwl.view.ui.activity.self.publish;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;

import android.graphics.Color;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityLeaseFactoryBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.lease.AskLeaseItemEntity;
import com.sgb.kjwl.model.entity.self.LeaseFactoryEntity;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.transport.MapLongAndLatEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.ServiceEntity;
import com.sgb.kjwl.model.entity.user.UnitEntity;
import com.sgb.kjwl.utils.EditInputFilter;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.kjwl.view.ui.adapter.self.publish.ImageAdapter;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.viewmodel.self.publish.LeaseFactoryModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.CommonDialog;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

/**
 * 工厂出租发布
 */
public class LeaseFactoryActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {
    @Inject
    LeaseFactoryModel viewModel;
    private ActivityLeaseFactoryBinding binding;
    // 地址一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 地址二级联动数据
    private final List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    // 地址三级联动数据
    private final List<List<List<AddressEntity>>> opt3 = new ArrayList<>();
    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;
    //价格列表
    private List<UnitEntity> unitEntityList;
    private final List<PickSelectEntity> classDatas = new ArrayList<>();
    private final List<List<PickSelectEntity>> typeDatas = new ArrayList<>();
    private List<PickSelectEntity> invoiceDatas, invoiceGGDatas;
    private List<PickSelectEntity> tariffDatas = new ArrayList<>();
    private List<PickSelectEntity> departmentData = new ArrayList<>();//申请部门列表
    private List<ServiceEntity> serviceEntities;//客服列表
    private List<DictEntity3> floorEntities;//楼层列表
    private List<DictEntity3> fireLevelEntities;//防火等级列表
    private List<LocalMedia> selectList = new ArrayList<>();
    private final List<File> fileList = new ArrayList<>();
    private final List<String> urls = new ArrayList<>();
    public int imgTotal;
    private int currentImgNum;
    private final List<String> uploadImgList = new ArrayList<>();
    private ImageAdapter adapter;
    private String area = "";
    private String id = "";
    private int unitPosition;
    private String updateUserNo;
    private boolean isApprove = false;//是否需要审批
    private String myCompanyNo;

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder().appComponent(appComponent)
                .selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    public static void start(Context context) {
        start(context, null);
    }

    public static void start(Context context, String id) {
        Intent intent = new Intent(context, LeaseFactoryActivity.class);
        intent.putExtra("id", id);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置沉浸式状态栏的上移问题
        setTileImmerse(true);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_lease_factory);
        binding.setViewModel(viewModel);
        binding.topLayout.titleView.setText("工厂出租发布");
        binding.topLayout.ivBack.setOnClickListener(v -> onBackPressed());
        binding.include.tvUse.setOnClickListener(this);
        binding.btnSave.setOnClickListener(this);
        binding.btnSubmit.setOnClickListener(this);
        binding.itemTvDepartmentName.setOnWholeItemClickListener(this);
        binding.houseType.setOnWholeItemClickListener(this);
        binding.houseFloor.setOnWholeItemClickListener(this);
        binding.houseLevel.setOnWholeItemClickListener(this);
        binding.houseAddress.setOnWholeItemClickListener(this);
        binding.itemTvInvoice.setOnWholeItemClickListener(this);
        binding.itemTvInvoiceGg.setOnWholeItemClickListener(this);
        binding.itemTvSl.setOnWholeItemClickListener(this);
        //租赁价格的点击事件
        binding.tvPriceUnit.setOnClickListener(this);
        binding.houseArea.setFilters(new EditInputFilter[]{new EditInputFilter()});
        binding.etStartMonth.setFilters(new EditInputFilter[]{new EditInputFilter(99, 1, 0)});
        binding.leasePrice.setFilters(new EditInputFilter[]{new EditInputFilter(99999999.99, 2)});
        binding.houseAddressDetail.setOnWholeItemClickListener(this);
        binding.serviceName.setOnWholeItemClickListener(this);
        binding.rbPrice.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {//面议还是报价功能
                    binding.rbPrice.setButtonDrawable(R.mipmap.lease_pub_select);
                    binding.layoutPrice.setVisibility(View.GONE);
                    binding.rbPrice.setText("您已选择面议，再次点击退出面议");
                } else {
                    binding.rbPrice.setButtonDrawable(R.mipmap.lease_pub_unselect);
                    binding.layoutPrice.setVisibility(View.VISIBLE);
                    binding.rbPrice.setText("面议");
                }
            }
        });

        binding.rbStartMonth.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    binding.rbStartMonth.setButtonDrawable(R.mipmap.lease_pub_select);
                    binding.layoutStartMonth.setVisibility(View.GONE);
                    binding.rbStartMonth.setText("您已选择面议，再次点击退出面议");
                } else {
                    binding.rbStartMonth.setButtonDrawable(R.mipmap.lease_pub_unselect);
                    binding.layoutStartMonth.setVisibility(View.VISIBLE);
                    binding.rbStartMonth.setText("面议");
                }
            }
        });

        binding.rbPay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    binding.rbPay.setButtonDrawable(R.mipmap.lease_pub_select);
                    binding.layoutPay.setVisibility(View.GONE);
                    binding.rbPay.setText("您已选择面议，再次点击退出面议");
                } else {
                    binding.rbPay.setButtonDrawable(R.mipmap.lease_pub_unselect);
                    binding.layoutPay.setVisibility(View.VISIBLE);
                    binding.rbPay.setText("面议");
                }
            }
        });

        //        房产面积
        binding.houseArea.setOnFocusChangeListener(new View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    // 此处为失去焦点时的处理内容
                    area = binding.houseArea.getText().toString();
                    setDefaultTitle();
                }
            }
        });

        adapter = new ImageAdapter(this, null, null, 5);
        binding.recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        binding.recyclerView.setAdapter(adapter);
    }

    @Override
    protected void init() {
        initInvoiceData();
        initDefault();
        id = getIntent().getStringExtra("id");
        if (!TextUtils.isEmpty(id)) {
            viewModel.getEditDetail(id);
            binding.topLayout.titleView.setText("工厂出租编辑");
        }
        viewModel.getAddressModel();//请求省市区数据
        viewModel.getTypeModel();//数据类型
        viewModel.getPriceUnitModel();
        viewModel.getLeaseRate();//税率
        initDepartment();
    }

    private void initDepartment() {
        updateUserNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
        myCompanyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        String myCompanyName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "");
        String contact = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.REAL_NAME, "");
        String loginPhone = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, "");
        binding.itemTvDepartmentUnit.setContent(myCompanyName);
        binding.itemTvDepartmentPerson.setContent(contact);
        binding.itemTvContact.setContent(contact);
        binding.itemTvPhone.setContent(loginPhone);
        //企业用户获取申请 部门
        if (!TextUtils.isEmpty(myCompanyNo) && !"0".equals(myCompanyNo)) {
            viewModel.getDepartment();
            binding.itemTvDepartmentUnit.setVisibility(View.VISIBLE);
            binding.itemTvDepartmentName.setVisibility(View.VISIBLE);
            binding.itemTvDepartmentPerson.setVisibility(View.VISIBLE);
        }
    }

    //初始化发票选择数据
    private void initInvoiceData() {
        //是否选择发票（0:是;1:否）
        invoiceDatas = new ArrayList<>();
        invoiceDatas.add(new PickSelectEntity("1", "是"));
        invoiceDatas.add(new PickSelectEntity("0", "否"));
        //发票类型
        invoiceGGDatas = new ArrayList<>();
        invoiceGGDatas.add(new PickSelectEntity("0", "普通发票"));
        invoiceGGDatas.add(new PickSelectEntity("1", "专用发票"));
    }

    //设置默认参数
    private void initDefault() {
        binding.itemTvInvoice.setContent("是");
        binding.itemTvInvoiceGg.setContent("普通发票");
        Objects.requireNonNull(viewModel.addLeaseFactoryEntity.get()).setNeedInvoice("1");
        Objects.requireNonNull(viewModel.addLeaseFactoryEntity.get()).setInvoiceType("0");
    }

    //设置编辑返显数据
    @SuppressLint("SetTextI18n")
    public void showEdit(LeaseFactoryEntity entity) {
        viewModel.addLeaseFactoryEntity.set(entity);

        if (!TextUtils.isEmpty(entity.getDepartmentName()) && updateUserNo.equals(entity.getUpdateUserNo())) {
            binding.itemTvDepartmentName.setContent(entity.getDepartmentName());
        } else {
            viewModel.addLeaseFactoryEntity.get().setDepartmentNo("");
            viewModel.addLeaseFactoryEntity.get().setDepartmentName("");
        }

        if (!TextUtils.isEmpty(entity.getSecondCategoryName())) {
            binding.houseType.setContent(entity.getFirstCategoryName() + " " + entity.getSecondCategoryName());
        } else {
            binding.houseType.setContent(entity.getFirstCategoryName());
        }
        if (!TextUtils.isEmpty(entity.getCustomerName())) {
            binding.serviceName.setContent(entity.getCustomerName());
        }
        if (!TextUtils.isEmpty(entity.getPriceUnitName())) {
            binding.tvPriceUnit.setText(entity.getPriceUnitName());
        }
        //所在区域
        if (!TextUtils.isEmpty(entity.getPcaName())) {
            binding.houseAddress.setContent(entity.getPcaName());
        }
        //楼层
        if (!TextUtils.isEmpty(entity.getFloorType())) {
            binding.houseFloor.setContent(entity.getFloorTypeName());
        }
        //防火等级
        if (!TextUtils.isEmpty(entity.getFireLevel())) {
            binding.houseLevel.setContent(entity.getFireLevelName());
        }

        //设置预付方式
        if ("面议".equals(entity.getPayType()) || "-1".equals(entity.getPayType())) {
            binding.etPay.setText("");
            binding.rbPay.setChecked(true);
            binding.rbPay.setText("您已选择面议，再次点击退出面议");
            binding.layoutPay.setVisibility(View.GONE);
        } else if (!TextUtils.isEmpty(entity.getPayType())) {
            binding.etPay.setText(entity.getPayType());
            binding.rbPay.setText("面议");
            binding.rbPay.setChecked(false);
            binding.layoutPay.setVisibility(View.VISIBLE);
        }

        //设置起租期
        if ("-1".equals(entity.getRentalDate())) {
            binding.etStartMonth.setText("");
            binding.rbStartMonth.setChecked(true);
            binding.rbStartMonth.setText("您已选择面议，再次点击退出面议");
            binding.layoutStartMonth.setVisibility(View.GONE);
        } else {
            binding.etStartMonth.setText(entity.getRentalDate());
            binding.rbStartMonth.setChecked(false);
            binding.rbStartMonth.setText("面议");
            binding.layoutStartMonth.setVisibility(View.VISIBLE);
        }

        //是否面议
        try {
            double rentalPriceInt;
            if (entity.getRentalPrice() != null) {
                rentalPriceInt = Double.valueOf(entity.getRentalPrice());
                if (rentalPriceInt <= 0) {
                    binding.leasePrice.setText("");
                    binding.rbPrice.setChecked(true);
                    binding.rbPrice.setText("您已选择面议，再次点击退出面议");
                    binding.layoutPrice.setVisibility(View.GONE);
                } else {
                    binding.leasePrice.setText(entity.getRentalPrice());
                    binding.rbPrice.setChecked(false);
                    binding.rbPrice.setText("面议");
                    binding.layoutPrice.setVisibility(View.VISIBLE);
                }
            }
        } catch (Exception e) {
        }

        if ("1".equals(viewModel.addLeaseFactoryEntity.get().getNeedInvoice())) {
            binding.itemTvInvoice.setContent("是");
            binding.itemTvSl.setVisibility(View.VISIBLE);
            binding.itemTvSl.setContent(viewModel.addLeaseFactoryEntity.get().getTariff() + "%");
            binding.itemTvInvoiceGg.setVisibility(View.VISIBLE);
            if ("0".equals(viewModel.addLeaseFactoryEntity.get().getInvoiceType())) {
                binding.itemTvInvoiceGg.setContent("普通发票");
            } else {
                binding.itemTvInvoiceGg.setContent("专用发票");
            }
        } else if ("0".equals(viewModel.addLeaseFactoryEntity.get().getNeedInvoice())) {
            binding.itemTvInvoice.setContent("否");
            binding.itemTvInvoiceGg.setVisibility(View.GONE);
            binding.itemTvSl.setVisibility(View.GONE);
        } else {//如果没有没有数据,代表是新发布,默认开具发票
            binding.itemTvInvoice.setContent("是");
            binding.itemTvInvoiceGg.setContent("普通发票");
            Objects.requireNonNull(viewModel.addLeaseFactoryEntity.get()).setNeedInvoice("1");
            Objects.requireNonNull(viewModel.addLeaseFactoryEntity.get()).setInvoiceType("0");
        }

        binding.houseAddress.setContent(viewModel.addLeaseFactoryEntity.get().getPcaName());
        binding.houseAddressDetail.setContent(viewModel.addLeaseFactoryEntity.get().getTaskAddr());

        //获取填写的标题
        if (!TextUtils.isEmpty(viewModel.addLeaseFactoryEntity.get().getTitle())) {
            binding.include.itemTvTitleEdit.setEditContent(viewModel.addLeaseFactoryEntity.get().getTitle());
        }

        //设置图片
        if (viewModel.addLeaseFactoryEntity.get().getImgPathList() != null && viewModel.addLeaseFactoryEntity.get().getImgPathList().size() > 0) {
            adapter.setNetImgList(viewModel.addLeaseFactoryEntity.get().getImgPathList());
        }
        setDefaultTitle();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_price_unit:
                hideKeyboard(binding.tvPriceUnit);
                showUnitPop(unitEntityList);
                break;
            case R.id.btn_save://暂存
                viewModel.addLeaseFactoryEntity.get().setState("0");
                validateData();
                break;
            case R.id.btn_submit://提交
                viewModel.addLeaseFactoryEntity.get().setState("1");
                validateData();
                break;
            case R.id.tv_use:
                binding.include.itemTvTitleEdit.setEditContent(binding.include.tvTitleDefault.getText().toString());
                break;
            default:
                break;
        }
    }

    /**
     * 弹出租赁价格单位选择框
     */
    public void showUnitPop(List<UnitEntity> list) {
        if (unitEntityList != null && unitEntityList.size() > 0) {
            OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
                String content = unitEntityList.get(options1).getName();
                binding.tvPriceUnit.setText(content);
                unitPosition = options1;
                Objects.requireNonNull(viewModel.addLeaseFactoryEntity.get()).setPriceUnitName(unitEntityList.get(options1).getName());
                Objects.requireNonNull(viewModel.addLeaseFactoryEntity.get()).setPriceUnitNo(unitEntityList.get(options1).getNo());

            }).build();
            businessOption.setPicker(unitEntityList);
            businessOption.setSelectOptions(unitPosition);
            businessOption.show();
        } else {
            //设置默认选项
            if (list != null && list.size() > 0) {
                binding.tvPriceUnit.setText(list.get(0).getName());
                Objects.requireNonNull(viewModel.addLeaseFactoryEntity.get()).setPriceUnitName(list.get(0).getName());//rentalSelectPrice
                Objects.requireNonNull(viewModel.addLeaseFactoryEntity.get()).setPriceUnitNo(list.get(0).getNo());//rentalSelectPrice
                this.unitEntityList = list;
            }
        }
    }

    //楼层
    public void showFloorSelect(List<DictEntity3> list) {
        if (list != null && list.size() > 0) {
            if ("全部".equals(list.get(0).getName()) || "不限".equals(list.get(0).getName()))
                list.remove(0);//因为所有权只有两类,第一个为全部或不限,需要删除
        }
        this.floorEntities = list;
        if (null != floorEntities && floorEntities.size() > 0) {
            OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
                String content = this.floorEntities.get(options1).getName();
                binding.houseFloor.setContent(content);
                Objects.requireNonNull(viewModel.addLeaseFactoryEntity.get()).setFloorType(this.floorEntities.get(options1).getId());
            }).build();
            businessOption.setPicker(list);
            businessOption.setSelectOptions(0);
            businessOption.show();
        }
    }

    //防火等级
    public void showFireLevelSelect(List<DictEntity3> list) {
        if (list != null && list.size() > 0) {
            if ("全部".equals(list.get(0).getName()) || "不限".equals(list.get(0).getName()))
                list.remove(0);//因为所有权只有两类,第一个为全部或不限,需要删除
        }
        this.fireLevelEntities = list;
        if (null != fireLevelEntities && fireLevelEntities.size() > 0) {
            OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
                String content = this.fireLevelEntities.get(options1).getName();
                binding.houseLevel.setContent(content);
                Objects.requireNonNull(viewModel.addLeaseFactoryEntity.get()).setFireLevel(this.fireLevelEntities.get(options1).getId());
            }).build();
            businessOption.setPicker(list);
            businessOption.setSelectOptions(0);
            businessOption.show();
        }
    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.house_type://类型
                showClassTypePop();
                break;
            case R.id.house_floor://楼层
                if (floorEntities != null && floorEntities.size() > 0) {
                    showFloorSelect(floorEntities);
                } else {
                    viewModel.getFloorSelectModel();
                }
                break;
            case R.id.house_level://防火等级
                if (fireLevelEntities != null && fireLevelEntities.size() > 0) {
                    showFireLevelSelect(fireLevelEntities);
                } else {
                    viewModel.fireLevelSelectModel();
                }
                break;
            case R.id.house_address://地区
                if (addressEntityList != null) {
                    showCityPop("请选择地区");
                }
                break;
            case R.id.house_address_detail://详细地址
                if (!TextUtils.isEmpty(binding.houseAddress.getContent())) {
                    //跳转详细地址界面
                    viewModel.getLocationLL(
                            viewModel.addLeaseFactoryEntity.get().getProvinceNo(),
                            viewModel.addLeaseFactoryEntity.get().getCityNo(),
                            viewModel.addLeaseFactoryEntity.get().getAreaNo());
                } else {
                    MToast.showToast(this, "请选择所在地区");
                }
                break;
            case R.id.item_tv_invoice://选择发票
                if (null != invoiceDatas && invoiceDatas.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(LeaseFactoryActivity.this, (options1, options2, options3, v) -> {
                        String content = invoiceDatas.get(options1).getProjectscale();
                        binding.itemTvInvoice.setContent(content);
                        Objects.requireNonNull(viewModel.addLeaseFactoryEntity.get()).setNeedInvoice(invoiceDatas.get(options1).getNo());
                        if ("否".equals(content)) {
                            binding.itemTvInvoiceGg.setVisibility(View.GONE);
                            binding.itemTvSl.setVisibility(View.GONE);
                        } else {
                            binding.itemTvInvoiceGg.setVisibility(View.VISIBLE);
                            binding.itemTvSl.setVisibility(View.VISIBLE);
                        }
                    }).build();
                    businessOption.setPicker(invoiceDatas);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
            case R.id.item_tv_invoice_gg://发票类型
                if (null != invoiceGGDatas && invoiceGGDatas.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(LeaseFactoryActivity.this, (options1, options2, options3, v) -> {
                        String content = invoiceGGDatas.get(options1).getProjectscale();
                        binding.itemTvInvoiceGg.setContent(content);
                        Objects.requireNonNull(viewModel.addLeaseFactoryEntity.get()).setInvoiceType(invoiceGGDatas.get(options1).getNo());
                    }).build();
                    businessOption.setPicker(invoiceGGDatas);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
            case R.id.item_tv_sl://税率
                if (null != tariffDatas && tariffDatas.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(LeaseFactoryActivity.this, (options1, options2, options3, v) -> {
                        String content = tariffDatas.get(options1).getProjectscale();
                        binding.itemTvSl.setContent(content);
                        viewModel.addLeaseFactoryEntity.get().setTariff(tariffDatas.get(options1).getNo());
                    }).build();
                    businessOption.setPicker(tariffDatas);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
            case R.id.item_tv_department_name://申请部门
                if (null != departmentData && departmentData.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(LeaseFactoryActivity.this,
                            (options1, options2, options3, v) -> {
                                String content = departmentData.get(options1).getProjectscale();
                                binding.itemTvDepartmentName.setContent(content);
                                viewModel.addLeaseFactoryEntity.get().setDepartmentNo(departmentData.get(options1).getNo());
                                viewModel.addLeaseFactoryEntity.get().setDepartmentName(content);
                            }).build();
                    businessOption.setPicker(departmentData);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                } else {
                    MToast.showToast(LeaseFactoryActivity.this, "暂无申请部门");
                }
                break;
            case R.id.service_name://咨询客服
                if (this.serviceEntities == null) {
                    viewModel.getCustomerOrgDataS();
                } else {
                    getCustomerOrgDataS(serviceEntities);
                }
                break;
            default:
                break;
        }
    }

    //    选择地址弹窗
    private void showCityPop(String title) {
        CityPickView cityOption = new CityPickBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String areaName = "";
                if (opt3.get(options1).get(options2).get(options3) == null) {
                    areaName = "";
                } else {
                    areaName = opt3.get(options1).get(options2).get(options3).getName();
                    cityPosition3 = options3;
                    Objects.requireNonNull(viewModel.addLeaseFactoryEntity.get()).setAreaNo(opt3.get(options1).get(options2).get(options3).getNo());
                    Objects.requireNonNull(viewModel.addLeaseFactoryEntity.get()).setAreaName(opt3.get(options1).get(options2).get(options3).getName());
                }
                String content = addressEntityList.get(options1).getName() + " / " + opt2.get(options1).get(options2).getName() + " / " + areaName;
                cityPosition1 = options1;
                cityPosition2 = options2;
//                rentAddress = new PublishLeaseDataEntity.RentAddress();
//                if (!TextUtils.isEmpty(areaName)) {
//                    rentAddress.setAreaId(opt3.get(options1).get(options2).get(options3).getNo());
//                }
//                rentAddress.setProvinceId(addressEntityList.get(options1).getId());
//                rentAddress.setCityId(opt2.get(options1).get(options2).getNo());
//                rentAddress.setRentalAddress(content);
                binding.houseAddress.setContent(content);
                binding.houseAddressDetail.setContent("");
                binding.houseAddressDetail.setHint("请输入详细地址（必选）");
                Objects.requireNonNull(viewModel.addLeaseFactoryEntity.get()).setProvinceNo(addressEntityList.get(options1).getNo());
                Objects.requireNonNull(viewModel.addLeaseFactoryEntity.get()).setCityNo(opt2.get(options1).get(options2).getNo());
                Objects.requireNonNull(viewModel.addLeaseFactoryEntity.get()).setProvinceName(addressEntityList.get(options1).getName());
                Objects.requireNonNull(viewModel.addLeaseFactoryEntity.get()).setCityName(opt2.get(options1).get(options2).getName());
            }
        }).setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleText(title)
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    //返回省市区数据加载数据
    public void initAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        addressEntityList = data;
        initJsonData();
    }

    //组装省市区数据信息
    private void initJsonData() {
        for (int i = 0; i < addressEntityList.size(); i++) {
            ArrayList areaList = new ArrayList<>();
            opt2.add(addressEntityList.get(i).getChildren());
            for (int j = 0; j < addressEntityList.get(i).getChildren().size(); j++) {
                List<AddressEntity> cityAreaList = new ArrayList<>();
                List<AddressEntity> children = addressEntityList.get(i).getChildren().get(j).getChildren();
                if (children == null || children.size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(children);
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
    }


    private void validateData() {
        //发布数据
        if (TextUtils.isEmpty(binding.houseType.getContent())) {
            MToast.showToast(this, "请选择工厂分类");
            return;
        } else if (TextUtils.isEmpty(binding.houseFloor.getContent())) {
            MToast.showToast(this, "请选择楼层");
            return;
        } else if (TextUtils.isEmpty(binding.houseLevel.getContent())) {
            MToast.showToast(this, "请选择防火等级");
            return;
        } else if (TextUtils.isEmpty(binding.houseArea.getText().toString())) {
            MToast.showToast(this, "请输入面积");
            return;
//        } else if (Double.parseDouble(binding.houseArea.getText().toString()) <= 0) {
//            MToast.showToast(this, "请输入正确面积");
//            return;
        } else if (TextUtils.isEmpty(binding.houseAddress.getContent())) {
            MToast.showToast(this, "请选择所在地区");
            return;
        } else if (TextUtils.isEmpty(binding.itemTvContact.getContent())) {
            MToast.showToast(this, "请输入联系人");
            return;
        } else if (TextUtils.isEmpty(binding.itemTvPhone.getContent())) {
            MToast.showToast(this, "请输入联系电话");
            return;
        } else if (!CheckUtils.isMobileNum(binding.itemTvPhone.getContent()) && !CheckUtils.IsTelephone(binding.itemTvPhone.getContent())) {
            Toast.makeText(this, "请输入正确的联系电话", Toast.LENGTH_SHORT).show();
            return;
        } else if (TextUtils.isEmpty(binding.houseAddressDetail.getContent())) {
            MToast.showToast(this, "请选择详细地址");
            //测试数据
//            binding.houseAddressDetail.setContent("陕西省西安市新城区南新街30");
//            viewModel.addLeaseFactoryEntity.get().setLatitude("34.269272");
//            viewModel.addLeaseFactoryEntity.get().setLongitude("108.9599");
//            viewModel.addLeaseFactoryEntity.get().setTaskAddr("陕西省西安市新城区南新街30");
            return;
        }

        //起租期
        if (binding.rbStartMonth.isChecked()) {
            viewModel.addLeaseFactoryEntity.get().setRentalDate("-1");
        } else {
            try {
                if (Double.parseDouble(binding.etStartMonth.getText().toString()) <= 0) {
                    MToast.showToast(this, "起租期必须大于0");
                }
            } catch (Exception e) {
            }
            viewModel.addLeaseFactoryEntity.get().setRentalDate(binding.etStartMonth.getText().toString().trim());
        }

        //预付方式
        if (binding.rbPay.isChecked()) {
            viewModel.addLeaseFactoryEntity.get().setPayType("面议");
        } else {
//            if (TextUtils.isEmpty(binding.etPay.getText())) {
//                MToast.showToast(this, "请输入预付方式");
//                return;
//            }
            viewModel.addLeaseFactoryEntity.get().setPayType(binding.etPay.getText().toString().trim());
        }

        if (binding.rbPrice.isChecked()) {
            viewModel.addLeaseFactoryEntity.get().setRentalPrice("-1");
        } else {
            if (TextUtils.isEmpty(binding.leasePrice.getText())) {
                MToast.showToast(this, "请输入租赁价格");
                return;
            } else if (Double.parseDouble(binding.leasePrice.getText().toString()) <= 0) {
                MToast.showToast(this, "请输入大于0的价格");
                return;
            } else {
                viewModel.addLeaseFactoryEntity.get().setRentalPrice(binding.leasePrice.getText().toString());
            }
        }

        if (binding.itemTvInvoice.getContent().equals("是") && TextUtils.isEmpty(binding.itemTvSl.getContent())) {
            Toast.makeText(this, "请选择税率", Toast.LENGTH_SHORT).show();
            return;
        }


        String title = binding.include.itemTvTitleEdit.getEditContent().trim();
        if (TextUtils.isEmpty(title)) {//如果自定义标题为空,则上传默认标题
//            viewModel.addLeaseFactoryEntity.get().setTitle(binding.include.tvTitleDefault.getText().toString());
            MToast.showToast(this, "请输入标题");
            return;
        } else {
            viewModel.addLeaseFactoryEntity.get().setTitle(title);
        }
        viewModel.addLeaseFactoryEntity.get().setRentalArea(binding.houseArea.getText().toString());
        viewModel.addLeaseFactoryEntity.get().setRemark(binding.leaseExpand.getEditContent());

        if (adapter.getItemCount() <= 1) {
            MToast.showToast(this, "请上传图片");
            return;
        } else {
            uploadImgList.clear();
            if (adapter.getFileList().size() != 0) {
                currentImgNum = 0;
                uploadImgList.clear();
                imgTotal = adapter.getFileList().size();
                viewModel.uploadMutiFileModel(adapter.getFileList().get(currentImgNum), 0, currentImgNum + 1);
            } else {
                uploadImgSuccess(adapter.getUrls(), 1);
            }
        }

    }

    //图片单张上传
    public void uploadRefresh(String url, int type) {
        uploadImgList.add(url);
        if (currentImgNum + 1 == imgTotal) {
            uploadImgSuccess(uploadImgList, type);
        } else {
            currentImgNum++;
            viewModel.uploadMutiFileModel(adapter.getFileList().get(currentImgNum), 0, currentImgNum + 1);
        }
    }

    //图片上传成功回调
    public void uploadImgSuccess(List<String> urls, int type) {
        //拼接图片url
        List<String> urlList = new ArrayList<>();
        for (int i = 0; i < urls.size(); i++) {
            urlList.add(urls.get(i));
        }

        if (type == 0) {
            if (viewModel.addLeaseFactoryEntity.get().getImgPathList() != null) {
                viewModel.addLeaseFactoryEntity.get().getImgPathList().addAll(urlList);
                urlList.clear();
                urlList.addAll(viewModel.addLeaseFactoryEntity.get().getImgPathList());
            }
        }
        Objects.requireNonNull(viewModel.addLeaseFactoryEntity.get()).setImgPathList(urlList);
        if (TextUtils.isEmpty(viewModel.addLeaseFactoryEntity.get().getDepartmentNo())) {
            Objects.requireNonNull(viewModel.addLeaseFactoryEntity.get()).setDepartmentNo("");
        }
        currentImgNum = 0;

        //企业用户判断是否需要审批
        if (binding.itemTvDepartmentName.getVisibility() == View.VISIBLE && !"0".equals(viewModel.addLeaseFactoryEntity.get().getState())) {
            viewModel.haveApprovalOrNot(myCompanyNo, "factoryRelease");
        } else {
            //发布
            viewModel.addOrUpdateEstate();
            showReNext(false);
        }
    }

//    public void publishSuccess(){
//        PublishSuccessActivity.start(this,PublishSuccessActivity.PAGE_FACTORY);
//        finish();
//    }

    public void showReNext(boolean enabled) {
        binding.btnSave.setEnabled(enabled);
        binding.btnSubmit.setEnabled(enabled);
    }

    //设置默认标题
    private void setDefaultTitle() {
        if (!TextUtils.isEmpty(area)) {
            binding.include.tvTitleDefault.setText("出租" + binding.houseArea.getText() + "㎡" + binding.houseType.getContent());
        } else {
            binding.include.tvTitleDefault.setText("出租" + binding.houseType.getContent());
        }
        binding.include.rlLeaseTitle.setVisibility(View.VISIBLE);
    }

    // 分类
    private void showClassTypePop() {
        if (classDatas == null || classDatas.size() == 0) {
            return;
        }
        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            binding.houseType.setContent(classDatas.get(options1).getProjectscale());
            viewModel.addLeaseFactoryEntity.get().setFirstCategoryNo(classDatas.get(options1).getNo());
            setDefaultTitle();
        }).build();
        businessOption.setPicker(classDatas);
        businessOption.setSelectOptions(0, 0);
        businessOption.show();
    }

    //类型集合
    public void showTypeView(List<AskLeaseItemEntity<List<AskLeaseItemEntity>>> data) {
        if (data == null || data.size() == 0) {
            return;
        }
        for (AskLeaseItemEntity<List<AskLeaseItemEntity>> l : data) {
            PickSelectEntity entity = new PickSelectEntity();
            entity.setNo(l.getNo());
            entity.setProjectscale(l.getName());
            classDatas.add(entity);
            List<PickSelectEntity> childList = new ArrayList<>();
            for (AskLeaseItemEntity ll : l.getChildren()) {
                PickSelectEntity child = new PickSelectEntity();
                child.setNo(ll.getNo());
                child.setProjectscale(ll.getName());
                childList.add(child);
            }
            typeDatas.add(childList);
        }
    }

    //  返回经纬度信息
    public void getLocationLL(MapLongAndLatEntity data) {
        if (!TextUtils.isEmpty(data.getLat())) {
            if (!TextUtils.isEmpty(data.getLng())) {
                Intent intent = new Intent();
                intent.setClass(this, SelectAddressActivity.class);
                intent.putExtra(SelectAddressActivity.TITLE, "详细地址");
                intent.putExtra(SelectAddressActivity.HINT, "请输入地址");
                intent.putExtra(SelectAddressActivity.SAVE_TEXT, "确定");
                intent.putExtra(SelectAddressActivity.LATITUDE, Double.parseDouble(data.getLat()));
                intent.putExtra(SelectAddressActivity.LONGTITUDE, Double.parseDouble(data.getLng()));
                startActivityForResult(intent, 255);
            }
        }
    }

    //选择客服
    public void getCustomerOrgDataS(List<ServiceEntity> serviceEntities) {
        this.serviceEntities = serviceEntities;
        if (null != serviceEntities && serviceEntities.size() > 0) {
            OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
                String content = this.serviceEntities.get(options1).getName();
                binding.serviceName.setContent(content);
                viewModel.addLeaseFactoryEntity.get().setCustomerId(this.serviceEntities.get(options1).getId());
                viewModel.addLeaseFactoryEntity.get().setCustomerName(this.serviceEntities.get(options1).getName());
            }).build();
            businessOption.setPicker(this.serviceEntities);
            businessOption.setSelectOptions(0);
            businessOption.show();
        }
    }

    //税率
    public void showRate(List<PickSelectEntity> list) {
        tariffDatas = list;
    }

    //申请部门
    public void showDepartment(List<PickSelectEntity> list) {
        departmentData = list;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 255) {
                if (data == null) {
                    return;
                }
                double lat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0);
                double lon = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0);
                String address = data.getStringExtra(SelectAddressActivity.CURRENT_POSITION);
                binding.houseAddressDetail.setContent(address + "");
                viewModel.addLeaseFactoryEntity.get().setLatitude(lat + "");
                viewModel.addLeaseFactoryEntity.get().setLongitude(lon + "");
                viewModel.addLeaseFactoryEntity.get().setTaskAddr(address + "");
            } else if (requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片结果回调
                // 图片、视频、音频选择结果回调
                selectList = PictureSelector.obtainMultipleResult(data);
                fileList.clear();
                urls.clear();
                for (LocalMedia localMedia : selectList) {
                    File file = new File(localMedia.getRealPath());
                    fileList.add(file);
                    urls.add(localMedia.getRealPath());
                }
                adapter.setDatas(selectList, urls);
                adapter.setFileList(fileList);
            }
        }
    }

    public static void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }


    /**
     * 0.暂存:保存成功
     * 1.需要审批:提交成功(发布前提示需要审批对话框)
     * 2.不需要审批:发布成功(发布前提示不需要审批对话框)
     */
    public void showSuccess() {
        if ("0".equals(viewModel.addLeaseFactoryEntity.get().getState())) {
            MToast.showToast(this, "保存成功");
        } else if (isApprove) {
            MToast.showToast(this, "提交成功");
        } else {
            MToast.showToast(this, "发布成功");
        }
    }

    /**
     * 提示审批对话框
     *
     * @param b
     */
    public void showPublishTip(boolean b) {
        isApprove = b;
        String msg = b ? "确认提交当前审批业务？" : "当前内容不需要审核，提交后即发布，确认提交？";
        new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                .setTitle("系统提示")
                .setMsg(msg)
                .setDialogCallBack(new CommonDialog.DialogCallBack() {
                    @Override
                    public void onRightClick() {
                        //发布
                        viewModel.addOrUpdateEstate();
                        showReNext(false);
                    }

                    @Override
                    public void onLeftClick() {
                        return;
                    }
                }).show();
    }

    @Override
    public void onBackPressed() {
        if (!TextUtils.isEmpty(id)) {
            finish();
        } else {
            new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                    .setTitle("提示")
                    .setMsg("你确定要返回上一步吗？返回后填写的数据将无法保存。")
                    .setDialogCallBack(new CommonDialog.DialogCallBack() {
                        @Override
                        public void onRightClick() {
                            LeaseFactoryActivity.this.finish();
                        }

                        @Override
                        public void onLeftClick() {
                            return;
                        }
                    }).show();
        }
    }

}
